package com.ypf.service.impl;

import com.ypf.domain.LoginUser;
import com.ypf.domain.ResponseResult;
import com.ypf.domain.vo.LoginVo;
import com.ypf.service.LoginService;
import com.ypf.utils.JwtUtil;
import com.ypf.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    // 将Security 中配置的东西拿出来
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(LoginVo loginVo, String captcha) {
        String userName = loginVo.getUserName();
        String uploadCaptcha = loginVo.getCaptcha();
        String password = loginVo.getPassword();

        if (!uploadCaptcha.equals(captcha)){
            return new ResponseResult(HttpStatus.BAD_REQUEST.value(),"验证码错误");
        }


        // AuthenticationManager authenticate 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName,password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果没认证给出对应的提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }

        // 如果认证通过了 使用userid 生成一个jwt jwt 存入ResponseResult 返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();

        String jwt = JwtUtil.createJWT(userId);
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);

        // 把完整的用户信息存入redis userid 作为key
        redisCache.setCacheObject("login:"+userId,loginUser);

        return new ResponseResult(200,"登录成功",map);

    }


}
